package com.mobileares.midp.widgets.client.panel;

import com.google.gwt.dom.client.Document;
import com.google.gwt.dom.client.Style;
import com.google.gwt.event.logical.shared.ResizeEvent;
import com.google.gwt.event.logical.shared.ResizeHandler;
import com.google.gwt.event.shared.HandlerRegistration;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.*;

/**
 * Created by IntelliJ IDEA.
 * User: Tom
 * Date: 2011-4-2
 * Time: 14:41:11
 * To change this template use File | Settings | File Templates.
 */
public class GlassPanel extends Composite {
    private AbsolutePanel panel;
    private static GlassPanel instance = new GlassPanel();
    private HandlerRegistration resizeRegistration;
    private int count = 0;

    private GlassPanel() {
        panel = new AbsolutePanel();
        panel.setStyleName("glass");
        panel.getElement().getStyle().setPosition(Style.Position.ABSOLUTE);
        panel.getElement().getStyle().setLeft(0, Style.Unit.PX);
        panel.getElement().getStyle().setTop(0, Style.Unit.PX);
        initWidget(panel);
    }

    public static GlassPanel getInstance() {
        return instance;
    }

    public AbsolutePanel getWidget() {
        return panel;
    }

    public void show() {
        RootPanel.getBodyElement().appendChild(instance.getElement());
        glassResizer.onResize(null);
        resizeRegistration = Window.addResizeHandler(glassResizer);
        count++;
    }

    public void hidden() {
        if (--count != 0) return;
        RootPanel.getBodyElement().removeChild(instance.getElement());
        resizeRegistration.removeHandler();
    }

    private ResizeHandler glassResizer = new ResizeHandler() {
        public void onResize(ResizeEvent event) {
            Style style = instance.getElement().getStyle();

            int winWidth = Window.getClientWidth();
            int winHeight = Window.getClientHeight();

            // Hide the glass while checking the document size. Otherwise it would
            // interfere with the measurement.
            style.setDisplay(Style.Display.NONE);
            style.setWidth(0, Style.Unit.PX);
            style.setHeight(0, Style.Unit.PX);

            int width = Document.get().getScrollWidth();

            int height = Document.get().getScrollHeight();

            // Set the glass size to the larger of the window's client size or the
            // document's scroll size.
            style.setWidth(Math.max(width, winWidth), Style.Unit.PX);
            style.setHeight(Math.max(height, winHeight), Style.Unit.PX);

            // The size is set. Show the glass again.
            style.setDisplay(Style.Display.BLOCK);
        }
    };
}
